package cn.jiangjiesheng.bootstrap.gateway.commons;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static cn.jiangjiesheng.bootstrap.gateway.commons.GlobalConstants.SKIP_AUTH_CHECK;

/**
 * Created by dev@jiangjiesheng.cn on 2021/7/20  <br/>
 */
@Component
@Slf4j
public class HighestGlobalPreFilter implements GlobalFilter, Ordered {

    @Autowired
    private CommonService commonService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取当前浏览器中的域名
        String domain = exchange.getRequest().getURI().getHost();
        ServerHttpRequest.Builder requestBuilder = exchange.getRequest().mutate();
        // 把域名写入header
        requestBuilder.header("domain", domain);
        // 是否跳过鉴权
        requestBuilder.header(SKIP_AUTH_CHECK, commonService.isSkipAuth(exchange).toString());
        requestBuilder.header("SERVICE_NAME", commonService.readServiceName(exchange.getRequest()));
        exchange.getResponse().getHeaders().add("GATEWAY","yes");
        ServerHttpRequest request = requestBuilder.build();
        exchange.mutate().request(request);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
